"use client";

import {
  ActionType,
  PageContainer,
  ProColumns,
  ProTable,
  ProTableProps,
} from "@ant-design/pro-components";
import {
  Button,
  Card,
  Dropdown,
  Flex,
  message,
  Popconfirm,
  Space,
  Tag,
  Tree,
} from "antd";
import { useRouter } from "next/navigation";
import { useRequest } from "ahooks";
import { useRef, useState } from "react";
import { deleteUserApi, getUserListApi } from "@/lib/api/system/user";
import type { User } from "@/lib/api/system/user.d";
import { getDeptTreeApi } from "@/lib/api/system/dept";
import { EllipsisOutlined } from "@ant-design/icons";

export default function Page() {
  const router = useRouter();
  const actionRef = useRef<ActionType>();
  const [selectedDeptId, setSelectedDeptId] = useState<string | undefined>(
    undefined,
  );

  const { run: deleteUser } = useRequest(deleteUserApi, {
    manual: true,
    onSuccess: () => {
      message.success("删除成功");
      actionRef.current?.reload();
    },
    onError: () => {
      message.error("删除失败");
    },
  });

  const { data: deptTree } = useRequest(getDeptTreeApi);
  console.log(deptTree);

  const colums: ProColumns<User>[] = [
    {
      title: "用户名称",
      dataIndex: "userName",
      key: "userName",
    },
    {
      title: "用户昵称",
      dataIndex: "nickName",
      key: "nickName",
    },
    {
      title: "部门",
      dataIndex: "deptName",
      key: "deptName",
      search: false,
    },
    {
      title: "手机号码",
      dataIndex: "phonenumber",
      key: "phonenumber",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      hideInSearch: true,
      render: (_, record) => (
        <Tag color={record.status === "0" ? "green" : "red"}>
          {record.status === "0" ? "启用" : "停用"}
        </Tag>
      ),
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      hideInTable: true,
      valueEnum: {
        "0": "正常",
        "1": "停用",
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      valueType: "dateTime",
      width: 150,
      hideInSearch: true,
    },
    {
      title: "创建时间",
      dataIndex: "createdTime",
      valueType: "dateRange",
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            "params[beginTime]": value[0] + " 00:00:00",
            "params[endTime]": value[1] + " 23:59:59",
          };
        },
      },
    },
    {
      title: "操作",
      key: "action",
      search: false,
      width: 200,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => editHandler(record.deptId)}>
            修改
          </Button>
          <Popconfirm
            title="确定删除吗？"
            description="删除后将无法恢复！"
            onConfirm={() => {
              deleteUser(record.userId);
            }}
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
          <Dropdown
            trigger={["click"]}
            menu={{
              items: [
                {
                  label: "重置密码",
                  key: "resetPassword",
                },
                {
                  label: "分配角色",
                  key: "assignRole",
                },
              ],
            }}
          >
            <Button variant="link" color="pink">
              <EllipsisOutlined />
            </Button>
          </Dropdown>
        </Space>
      ),
    },
  ];

  const tree = (
    <Card className="mr-4">
      <Tree
        defaultExpandAll={true}
        key="id"
        showLine
        treeData={deptTree?.data || []}
        fieldNames={{ title: "label", key: "id" }}
        className="min-w-[200px]"
        onSelect={(selectedKeys) => {
          setSelectedDeptId(selectedKeys[0] as string);
          actionRef.current?.reload();
        }}
      ></Tree>
    </Card>
  );

  const proTableProps: ProTableProps<User, any> = {
    columns: colums,
    rowKey: "deptId",
    pagination: { pageSize: 10 },
    headerTitle: "部门列表",
    expandable: {
      defaultExpandAllRows: true,
    },
    actionRef: actionRef,
    options: {
      fullScreen: true,
    },
    toolBarRender: () => {
      return [
        <Button
          onClick={() => addHandler(selectedDeptId)}
          key="add"
          type="primary"
        >
          新增
        </Button>,
      ];
    },
    request: async (params) => {
      const res = await getUserListApi({ ...params, deptId: selectedDeptId });

      return {
        data: res.rows,
        success: true,
        total: res.total,
      };
    },
    onRequestError(e) {
      message.error(e.message);
    },
    tableRender: (props, defaultDom) => {
      return (
        <Flex>
          {tree}
          {defaultDom}
        </Flex>
      );
    },
  };

  const addHandler = (deptId?: string) => {
    router.push(`user/add?deptId=${deptId}`);
  };

  const editHandler = (deptId: number) => {
    router.push(`user/edit?deptId=${deptId}`);
  };

  return (
    <PageContainer
      header={{
        title: false,
      }}
    >
      <ProTable {...proTableProps} className="flex-1"></ProTable>
    </PageContainer>
  );
}
